package cn.worldyao.demo.controller;


import cn.worldyao.demo.entity.Members;
import cn.worldyao.demo.service.MembersService;
import cn.worldyao.demo.util.ReturnSet;
import cn.worldyao.demo.util.Tools;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.sun.xml.internal.ws.developer.MemberSubmissionAddressing;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yaozi
 * @since 2020-03-08
 */
@RestController
@RequestMapping("/members")
public class MembersController {
    @Autowired
    private MembersService membersService;

    @GetMapping("/list")
    public ReturnSet membersList() {
        List<Members> members = membersService.list();
        JSONArray array = JSONArray.parseArray(JSON.toJSONString(members));
        return ReturnSet.success(array);
    }


    @PostMapping("/addMember")
    public ReturnSet addMember(@RequestBody Members members) throws Exception {
        System.out.println(members);
        members.setCreateTime(LocalDateTime.now());
        boolean add = membersService.save(members);
        if (add) {
            System.out.println(12345);
            Tools.updateMembers(members.getMid());
            return ReturnSet.success();
        }
        return ReturnSet.fail();
    }

    @GetMapping("/memberId")
    public ReturnSet genMemberId() throws IOException {
        String newMemberId = Tools.getNewMemberId();
        if (!"ERROR".equals(newMemberId)) {
            return ReturnSet.success(newMemberId);
        }
        return ReturnSet.fail();
    }

}
